package com.storm.common.response

import com.fasterxml.jackson.databind.ObjectMapper
import com.storm.common.exception.StatusInfo
import com.storm.common.exception.StormException
import com.storm.common.jackson.toKtData
import java.util.*


val DEFAULT_SUCCESS_MSG = StatusInfo.OK.message()
val DEFAULT_SUCCESS_STATUS = StatusInfo.OK.status()
val DEFAULT_FAIL_MSG = StatusInfo.BUSINESS_ERROR.message()
val DEFAULT_FAIL_STATUS = StatusInfo.BUSINESS_ERROR.status()

/**
 * 包装成功
 */
fun <T> success(result: T? = null,status: Int= DEFAULT_SUCCESS_STATUS, msg: String = DEFAULT_SUCCESS_MSG): JSONResponse<T> {
    return build(msg = msg, status, result)
}
/**
 * build 返回包装类型
 */
fun <T> build(msg: String, status: Int, result: T?): JSONResponse<T> {
    return JSONResponse(result, status, System.currentTimeMillis(), msg)
}

/**
 * 包装失败
 */
fun <T> fail(result: T? = null, status: Int? = null, msg: String? = null): JSONResponse<T> {
    return build(
            msg ?: DEFAULT_FAIL_MSG,
            status ?: DEFAULT_FAIL_STATUS,
            result
    )
}

/**
 * 如果返回值不为成功，则抛出定义的异常
 */
inline fun <reified T> JSONResponse<T>.getOrThrow(objectMapper: ObjectMapper,
                                               errorDeal: (JSONResponse<T>) -> StormException): T? {
    if (status != StatusInfo.OK.status()) {
        throw errorDeal(this)
    }
    return result.toKtData(objectMapper)
}

/**
 * 获取返回值，并包装上层抛出的错误抛出
 */
inline fun <reified T> JSONResponse<T>.get(objectMapper: ObjectMapper): T? {
    return getOrThrow(objectMapper){ StormException(it.msg, it.status) }
}
